var temp = object(tempAbs);
temp.sampleInfos = [];
temp.address = true;

//判断当前是否是编辑功能
var isEdit=false;
temp.read = function(obj,bn){
	bn.setSampleInfos();

    isEdit=true;
	if (obj && obj.customerCode) {
		bn.setComboBox('customerCode', obj.customerCode);
	}
	$(".second-table .field input").each(function(){
		var id = $(this).attr('id');
		if(id && id.indexOf('sampleType_')<0){
			if($(this).hasClass('easyui-datebox')){
				bn.setDat(id);
			}else{
				var type = $(this).attr('type');
				if(type=='text' || type=='date' || type=='number'){
					bn.setVl(id);
				}
			}
		}
	});
	$(".second-table .field select").each(function(){
		var id = $(this).attr('id');
		bn.setSel(id);
	});
	if(obj.sampleType){
		var sampleTypeArr = obj.sampleType.split(',');
		$("input:checkbox[name^='sampleType_']").each(function(i){
			var id = $(this).attr('name');
			setCkArr(id,sampleTypeArr[i]);
		});
	}
	
	var all = {};
	$(".second-table .group-field input").each(function(){
		var id = $(this).attr('id');
		all[id.split('_')[0]] = 1;
	});

	for(var key in all){
		bn.setCkGrp(key);
	}

    //新生儿监护病房neonatalCareType5
    var neonatalType = bn.obj.neonatalCareType;
    $('#neonatalCareType_0').removeAttr('checked');
    $('#neonatalCareType_1').removeAttr('checked');
    if(neonatalType !=""){
        if(parseInt(neonatalType)  >= 1){

            $('#neonatalCareType_1').prop('checked', true);
            $("#nicuType").css("display","inline-block");
            $("#nicu").val(neonatalType);
            $("#deafBabyDesc").css("display","inline-block");
            $("#neonatalCareType5").val(bn.obj.neonatalCareType5);
        }else{

            $('#neonatalCareType_0').prop('checked', true);
        }
    }

    //母亲怀孕期感染信息
    var pregnancyInfectionId = bn.obj.pregnancyInfection;
    $("#pregnancyInfection_"+pregnancyInfectionId).attr('checked', true);

    //展示籍贯信息
    if(obj.nativePlace){
		var sf = obj.nativePlace.substring(0,obj.nativePlace.indexOf('省')+1);
		var sq = obj.nativePlace.substring(obj.nativePlace.indexOf('省')+1,obj.nativePlace.length);
		$('#nativePlace1').val(sf);
		$('#nativePlace2').val(sq);
	}

    //身份证信息不可更改
    $("#idCard").attr("disabled","disabled");

    //展示免费券编码
    $("div.coupon-box").removeAttr("onclick").html("<span>免费券编码：</span>"+obj.couponNum);
	//$("#saveBtn").hide();
}

//生成新生儿姓名
$("#sampleSex").change(function () {
    if($("#sampleSex").val() == 1){
        $("#sampleNameA").text($("#motherName").val() + "大子").attr("value",$("#motherName").val() + "大子");
        $("#sampleNameB").text($("#motherName").val() + "二子").attr("value",$("#motherName").val() + "二子");
        $("#sampleNameC").text($("#motherName").val() + "三子").attr("value",$("#motherName").val() + "三子");
    }else if($("#sampleSex").val() == 2){
        $("#sampleNameA").text($("#motherName").val() + "大女").attr("value",$("#motherName").val() + "大女");
        $("#sampleNameB").text($("#motherName").val() + "二女").attr("value",$("#motherName").val() + "二女");
        $("#sampleNameC").text($("#motherName").val() + "三女").attr("value",$("#motherName").val() + "三女");
    }
    $("#sampleNameDiv").show();
});
$("#motherName").change(function () {
    if($("#sampleSex").val() == 1){
        $("#sampleNameA").text($("#motherName").val() + "大子").attr("value",$("#motherName").val() + "大子");
        $("#sampleNameB").text($("#motherName").val() + "二子").attr("value",$("#motherName").val() + "二子");
        $("#sampleNameC").text($("#motherName").val() + "三子").attr("value",$("#motherName").val() + "三子");
    }else if($("#sampleSex").val() == 2){
        $("#sampleNameA").text($("#motherName").val() + "大女").attr("value",$("#motherName").val() + "大女");
        $("#sampleNameB").text($("#motherName").val() + "二女").attr("value",$("#motherName").val() + "二女");
        $("#sampleNameC").text($("#motherName").val() + "三女").attr("value",$("#motherName").val() + "三女");
    }
});

temp.save = function(bn){
	bn.getSampleInfos(temp.sampleInfos);
	// bn.getComboGrid('customerCode');
	bn.vl('sampleNum');
	$(".second-table .field input").each(function(){
		var id = $(this).attr('id');
		if(id && id.indexOf('sampleType_')<0){
			var type = $(this).attr('type');
			if($(this).hasClass('easyui-datebox')){
				bn.dat(id);
			}else{
				if(type=='text'){
					bn.vl(id);
				}else if(type=='date'){
					bn.vl(id);
				}else if(type=='number'){
					bn.vl(id);
				}
			}
		}
	});
	$(".second-table .field select").each(function(){
		var id = $(this).attr('id');
		bn.sel(id);
	});
	var sampleTypeArr = [];
	var countSampleType = {};
	$("input:checkbox[name^='sampleType_']").each(function(){
		countSampleType[$(this).attr('name')] = 1;
	});
	for(var key in countSampleType){
		var val = ckArr(key);
		if(val){
			sampleTypeArr.push(val);
		}
	}
	bn.obj.sampleType = sampleTypeArr.join(',');
	//处理单选框字段
	$(".group-field input").each(function(){
		if($(this).is(":checked")){
			var id = $(this).attr('id');
			var arr = id.split('_');
			bn.obj[arr[0]] = arr[1];
		}
	});
	if(bn.obj.nativePlace1){
		bn.obj['nativePlace'] = bn.obj.nativePlace1+'省'+bn.obj.nativePlace2+'市';
		delete bn.obj.nativePlace1;
		delete bn.obj.nativePlace2;
	}
	if(bn.obj.idCard){
		bn.obj.idCard  = bn.obj.idCard.toUpperCase();
	}
}
temp.validateAbs = function(m){
	var msg = '';
	if(m) msg += m;
	return msg;
}
//组合复选框变单选框
$(function(){
	var p1 = null;
	var sortIndex = 1;
	$(".sample-type").each(function(index){
		var trArr = $(this).parent().parent().parent().parent().find('tr');
		var tTrArr = [];
		for(var i=0;i<trArr.length;i++){
			tTrArr.push(trArr[i]);
		}
		if(index==0){
			p1 = $(this).parent()[0];
			$(this).children("input:eq(0)").attr('name',"sampleType_"+sortIndex);
		}else{
			if(p1 != $(this).parent()[0] && Math.abs(tTrArr.indexOf(p1.parentNode)-tTrArr.indexOf($(this).parent().parent()[0]))>1){
				sortIndex++;
			}
			p1 = $(this).parent()[0];
			$(this).children("input:eq(0)").attr('name',"sampleType_"+sortIndex);
		}
	});
	var countObj = {};//统计有多少组需要单选的checkbox
	$(".second-table .group-field input").each(function(){
		var name = $(this).attr("name");
		countObj[name] = 1;
	});
	$(".second-table .sample-type input").each(function(){
		var name = $(this).attr("name");
		countObj[name] = 1;
	});
	for(var key in countObj){
		$("input[type=checkbox][name='"+key+"']").click(function(){
			if($(this).is(':checked')){
				if($(this).siblings('input').length>0){
					$(this).siblings('input').attr('checked',false);
				}else{
					$(this).parent('span').siblings().children('input').attr('checked',false);
				}
			}
		});
	}
	$("input:checkbox[id^='product_']").each(function(){
		var id = $(this).attr('id');
		temp.sampleInfos.push({productCode:id.split('_')[1],projectCode:''});
	});

   // $("#saveBtn").show();
});

//下拉列表显示省市信息
var BASEURL = '';
$(function (){
    if(isEdit){
        var province=$("#nativePlace1").val();
        var city=$("#nativePlace2").val();
        if((province !="" && province != null) && (city != "" && city !=null)){
            $("#province option:selected").text(province);
            $("#city option:selected").text(city);
        }else{
            resetSelect($('#province'), '', 10);
        }
        //resetSelect($('#province'), $("#nativePlace1").val(), 10);
    }else{
        resetSelect($('#province'), '', 10);
    }

});

//省市区
function resetSelect(jq, parentId, defaultIdx) {
    var url = BASEURL+'/csfy/intf.do?method=getAddrs';
    if (parentId) {
        url = url + '&parentId=' + parentId;
    }
    var jqId = '#' + jq.attr('id');
    $.getJSON(url, function (data) {
        if (data.msg === 'success') {
            jq.empty();
            $.each(data.rows, function (i, item) {
                var option = $('<option></option>');
                option.attr('value', item['code']);
                option.text(item['name']);
                jq.append(option);
            });
            if (defaultIdx) {
                jq.get(0).selectedIndex = defaultIdx;
                //alert(defaultIdx);
            }

            if (jqId) {
                addressChange(jqId);
            }
            jq.selectpicker('refresh');

            //将选择的值放入隐藏文本框中，方便验证
            var province=$("#province option:selected").text();
            var city=$("#city option:selected").text();
            //alert(province + city);
            if(province != "" && city !=""){
                $("#nativePlace1").val(province);
                $("#nativePlace2").val(city);
            }
        }
    });
}
function addressChange(id) {
    var code = $(id).children('option:selected').attr('value')
    switch (id) {
        case '#province':
        {
            var defaultIdx = undefined;
            if (code == 43) {
                defaultIdx = 8;
            }
            resetSelect($('#city'), code, defaultIdx);

            break;
        }
        case '#city':
        {
            resetSelect($('#county'), code);
            $('#town').empty();
            $('#town').selectpicker('refresh');
            break;
        }

    }
}

//显示NICU病房类别
function showNicuType(obj){
    var typeId=obj.id;
    var typeName = typeId.substr(0,typeId.indexOf("_"));
    var currentType=$("#"+obj.id).data("value");
    $("#"+typeName+"-input").val(currentType);

    var isShow=$("#nicuType").css("display");
    if(currentType == "0"){
        $("#nicuType").hide();
    }
    else{
        if(isShow == "none"){
            $("#nicuType").css("display","inline-block");
        }else{
            $("#nicuType").hide();
        }
    }
}

//监护病房详细
function getNICU(){
    var nicuInfo = $("#nicuType option:selected").val();
    if(nicuInfo === "5"){
        $("#deafBabyDesc").css("display","inline-block");
    }else{
        $("#deafBabyDesc").hide();
    }
}
//获取怀孕期感染数据
function getChoice(obj){
    var typeId=obj.id;
    var typeValue = $("#"+obj.id).data("value");
    var typeName = typeId.substr(0,typeId.indexOf("_"));
    $("#"+typeName+"-input").val(typeValue);
}

//不使用优惠券
$(".no-coupon").click(function () {
    $("#idCard").removeAttr('disabled');
    $("#sampleName").removeAttr('disabled');
    $('#myModal').modal('hide');
    couponNum = '';
    $('.coupon-box').html('选择免费券');
});

//退出登录
function logout() {
    $.ajax({
        url: '/csfy/dologout.do',
        method: 'POST',
        success: function (res) {
            if (JSON.parse(res).code == 200) {
                window.location.href = "/csfy/index.do"
            }
        }
    })
}
//使用优惠券
var couponNum = '';

//受检者姓名
var sampleName = '';

function useCoupon(num) {
    //优惠券对应的身份证号码
    var id = $("#coupon-kw").val();
    //设置优惠券对应的身份证
    $("#idCard").val(id);
    //设置身份证输入框不可编辑
    $("#idCard").attr('disabled', 'disabled');

    //使用优惠券姓名
    $("#motherName").val(sampleName);
	$("#motherName").attr('disabled', 'disabled');

    $('#myModal').modal('hide');
    $('.coupon-box').html('免费券码：' + (num ? num : ''));

    //重置搜索列表
    $("#coupon-kw").val('');
    $(".coupon-list").html('');
    $(".empty-coupon").hide();

    couponNum = num;
}

//身份证号失去焦点
$("#idCard").blur(function () {
    var id = $("#idCard").val();
    $.ajax({
        method: 'POST',
        url: '/csfy/intf.do',
        data: {
            method: 'getDetailPresonInfo',
            id
        },
        success: function (res) {
            console.log(res)
            var couponList = '';
            sampleName = res.rows.name;
            if (res && res.code == 200) {
                var couponInfos = (res.rows && res.rows.couponInfos) || [];
                for(var i = 0;i < couponInfos.length;i++){
                    if(couponInfos[i].productCode == "DX0459" && couponInfos[i].status == 1){
                        couponNum = couponInfos[i].couponNum;
                    }
                }
            }
        }
    });
});
//TODO 根据证件搜索优惠券
function searchCoupons() {
    var id = $("#coupon-kw").val();
    if (id) {
        $.ajax({
            method: 'POST',
            url: '/csfy/intf.do',
            data: {
                method: 'getDetailPresonInfo',
                id
            },
            success: function (res) {
                console.log(res)
                var couponList = '';
                sampleName = res.rows.name;
                $(".coupon-list").html('');
                $(".empty-coupon").html('正在搜索...');
                if (res && res.code == 200) {
                    var couponInfos = (res.rows && res.rows.couponInfos) || [];
                    if (couponInfos.length > 0) {
                        var mData = {};
                        mData.rows = couponInfos;
                        var html = template('coupon-list', mData);
                        $(".coupon-list").html(html);
                        $(".empty-coupon").hide();
                    } else {
                        $(".empty-coupon").html('未找到当前证件名下的免费券');
                    }
                } else {
                    $(".empty-coupon").html('未找到当前证件名下的免费券');
                }
            }
        });
    } else {
        $(".coupon-list").html('');
        $(".empty-coupon").show();
        $(".empty-coupon").html('没有找到免费券');
    }
}

//选择使用优惠券
function chooseCoupon() {
    $('#myModal').modal('show');
}

var clinicalInfo=[];
function save(cover) {

    //获取当前页面的子页面里面的属性值
    var msg = temp.validate();
    //获取模板字段。
    var obj = temp.saveAbs();
    //报错并退出
    if (msg) {
        sysErrorShow(msg);
        return false;
    }

    //数据过滤 start
    var params = {};
    Object.keys(obj).map(key => {
        var prototype = Object.prototype.toString.call(obj[key]);
    if ('[object String]' === prototype && obj[key]) {
        params[key] = obj[key];
    }
});
    params.productName = '耳聋基因检测';
    params.productCode = 'DX0459';
    if (couponNum) {
        params.couponNum = couponNum;
    }else {
        alert("您没有可使用的耳聋基因检测免费券，不能进行此操作");
        return false;
    }

    //新增新生儿病房
    var sickRoom = params.neonatalCareType=$("#neonatalCareType-input").val();
    if(sickRoom == "1"){
        if($("#nicu option:selected").val() != ""){
            var nicu = $("#nicu option:selected").val();
            params.neonatalCareType = nicu;
            if(nicu == "5"){
                var desc=$("#neonatalCareType5").val();
                if(desc != ""){
                    params.neonatalCareType5 = desc;//neonatalCareType5
                }else{
                    alert("请输入新生儿监护病房信息!");
                    return false;
                }
            }
        }
    }


    if($("#notes").val().length > 0){
        params.notes = $("#notes").val();
    }

    //修改怀孕期感染信息
    var infectInfo =$("#pregnancyInfection-input").val();
    if( infectInfo !=""){
        params.pregnancyInfection=infectInfo;
        if(infectInfo == "5"){
            var infectDesc = $("#pregnancyInfectionInfo").val();
            if(infectDesc !=""){
                params.pregnancyInfectionInfo =infectDesc;//pregnancyInfectionInfo
            }else{
                alert("请输入母亲怀孕期感染类型!");
                return false;
            }
        }
    }

    if($("#idCard").val() !=""){
        params.idCard=$("#idCard").val();//母亲身份证号码信息
        params.dnaMotherIdCard=$("#idCard").val();//母亲身份证号码信息
    }

    //获取省市信息
    var province=$("#nativePlace1").val();
    var city=$("#nativePlace2").val();
    // alert(province + city);
    var nativePlaceInfo = province + city;
    var isTrueNative = confirm("确定籍贯为："+nativePlaceInfo +"？提交后无法修改，请仔细核对！");
    if(isTrueNative){
        if(province != "" && city !=""){
            params.nativePlace = province + city;
        }else{
            alert("请填写正确的籍贯信息！");
            return false;
        }
    }else {
        return false;
    }


    //获取民族信息
    var nationalityInfo = $("#getNationaltily").val();
    if(nationalityInfo != ""){
        params.nationaltily = nationalityInfo;
    };

    //设置模板文件路径，对应前端工作平台1.0的模板服务器路径
    params.fileVer = "temp/deaf.jsp";
    params.sourceType='1';

    //数据过滤 end  updateSampleBaseBySampleBaseId
    //alert(JSON.stringify(params));
    $.ajax({
            type: 'POST',
            data: {
                method: isEdit ? 'updateExportSampleBases' : 'createSampleBase',
                ...params,
            sampleBaseId: isEdit ? sampleBaseId : undefined
        },
        url: '/csfy/intf.do',
        error: function (e) {
        sysErrorShow('操作失败!');
        },
        success: function (res) {
        //console.log(res);

        if (res && res.code == 200) {
            alert(isEdit ? "修改送检单成功" : "保存送检单成功");
            if (!isEdit){
                window.location.href = window.location.pathname;
            }
            else{
                sessionStorage.setItem("sampleEditSuccess", "true");
            }


        } else if (res) {
            alert(res.msg ? res.msg : "操作失败")
        }
    }
     });
   }



//获取当前登录用户信息
$(document).ready(function () {
    $.ajax({
        method: 'POST',
        url: '/csfy/intf.do',
        data: { method: 'getLoginUserInfo' },
        success: res => {
        if (res.code == 10086) {
            alert("请重新登录！");
        } else {
            if (res.code == 200) {
                $(".username").html(res.rows.userName);
            }
        }
        }
    })
})

